<template>
    <section>
        <section class="contact-detail-wrapper" v-if="props.previewData && chatState.currentChatTargetId > 0">
            <img class="contact-detail-user-avatar" @error="defaultAvatar" v-show="props.previewData.friendAvatar"
                :src="props.previewData.friendAvatar || defaultAvatar()" alt="">
            <p v-show="props.previewData.friendName" class="friends-info">
                <span>昵称：</span><span>{{ props.previewData.friendName }}</span>
            </p>
            <p v-show="props.previewData.friendNickname" class="friends-info">
                <span>昵称：</span><span>{{ props.previewData.friendNickname }}</span>
            </p>
            <p v-show="props.previewData.friendEmail" class="friends-info">
                <span>邮箱：</span><span>{{ props.previewData.friendEmail }}</span>
            </p>
            <section style="padding-top: 50px;" v-show="props.previewData.friendEmail">
                <el-button type="primary" :icon="ChatRound" @click="sendMessage">发消息</el-button>&emsp;
                <el-button type="primary" :icon="Document" @click="historyMessage">历史聊天记录</el-button>&emsp;
                <el-button type="danger" :icon="Delete" @click="dialogVisible = true">删除该好友</el-button>
            </section>
        </section>

        <el-dialog style="padding: 20px !important;" v-model="dialogVisible" title="备注信息" width="40%"
            :before-close="handleClose">
            <section style="width: 100%;">
                <h2>{{ previewStatus == 'remove' ? '提示' : '查看聊天记录' }}</h2>
                <p class="tip-message" v-show="previewStatus == 'remove'">确定删除该好友吗？</p>
                <section v-show="previewStatus == 'history'" class="infinite-list" style="overflow: auto; height: 300px;">
                    <DynamicScroller class="output-content-container" :min-item-size="54" :item-size="140" :items="items"
                        @scroll-end="scrollEnd">

                        <template v-slot="{ item, index, active }">
                            <DynamicScrollerItem :size="50" :active="active">
                                <HistoryChatItem :messageData="item" :key="index" :user-id="chatState.getUserInfo()?.id" />
                            </DynamicScrollerItem>

                        </template>
                    </DynamicScroller>
                </section>
            </section>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmHandle" v-show="previewStatus == 'remove'">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </section>
</template>

<script setup>
import { ChatMessage } from '@/stores/chat';
import { defaultAvatar, formatTime } from '@/utils';
import { ChatRound, Delete, Document } from "@element-plus/icons-vue";
import { ElNotification } from 'element-plus';
import { DynamicScroller, } from "vue-virtual-scroller";
import "vue-virtual-scroller/dist/vue-virtual-scroller.css";

import HistoryChatItem from "./HistoryChatItem.vue";

const page = ref(1)
const limit = ref(10)
const chatMessageTotal = ref(0)
const chatState = ChatMessage()
const dialogVisible = ref(false)
const previewStatus = ref('remove')
const props = defineProps({
    previewData: {
        type: Object,
        default: () => ({})
    }
})
const list = ref([])

const cmit = defineEmits(['updateView'])

const items = computed(() => {
    return list.value.map((item, index) =>
        Object.assign({}, { id: `data-id-${index}` }, item),
    );
});

watch(() => dialogVisible.value, (nVal) => {
    if (!nVal) {
        list.value = []
        page.value = 1
        chatMessageTotal.value = 0
    }
})

const handleClose = () => {
    previewStatus.value = 'remove'
}

const confirmHandle = async () => {
    let res = await useMyFetchDeleteMultipart("/api/chat-friends", {
        body: {
            friendId: props.previewData.friendId
        }
    }).catch(err => {
        ElNotification({ title: '提示', message: '删除失败', type: 'error' })
    })
    if (res.result) {
        chatState.getFriendsList()
        ElNotification({ title: '提示', message: '删除成功', type: 'success' })
        dialogVisible.value = false
        cmit('updateView')
        chatState.setCurrentChatName('')
        chatState.removeCurrentChat(props.previewData.friendId)
        chatState.removeCurrentChatMessage(props.previewData.friendId)
    }
}

const historyMessage = async () => {
    previewStatus.value = 'history'
    dialogVisible.value = true
    getHistoryMessageList()
}

const sendMessage = () => {
    chatState.changeTagStatus('chat')
    chatState.setChatType(1)
    chatState.addChatList({
        lastMessage: '',
        friendId: props.previewData.friendId,
        time: formatTime(new Date(), 'HH:mm',),
        ready: true,
        value: 0,
        chatType: 1,
        ...props.previewData
    })
    chatState.updateCurrentMessageList()
}

const scrollEnd = (e) => {
    page.value++
    getHistoryMessageList()
}

const getHistoryMessageList = async () => {
    if (list.value.length > 0 && (list.value.length == chatMessageTotal.value)) {
        return
    }
    let { results = [], page: { total = 0 } } = await useHttpGet(`/api/chat-friends/record`, {
        params: {
            page: page.value,
            limit: limit.value,
            friendId: props.previewData.friendId
        }
    })
    chatMessageTotal.value = total
    if (results.length) {
        results = results.map(item => ({ ...item, time: formatTime(new Date(item.createdAt), 'YYYY-MM-DD HH:mm') }))
        list.value = [...list.value, ...results]
    }
}


</script>

<style scoped lang="scss">
.contact-detail-wrapper {
    display: flex;
    flex: 1;
    flex-direction: column;
    width: 100%;
    align-items: center;
    flex-wrap: wrap;
    color: #888;
    padding-top: 150px;
}

.output-content-container {
    height: 300px;
}

.tip-message {
    font-weight: normal;
    margin-top: 20px;
    color: #296218;
}

.contact-detail-user-avatar {
    min-height: 50px;
    height: 50px;
    width: 50px;
    object-fit: cover;
    display: block;
    margin-bottom: 30px;

}
</style>